package com.treetao.union.core.tencent.mp.kit;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.treetao.union.core.exception.DevMException;
import com.treetao.union.core.redis.RedisService;
import com.treetao.union.core.util.HttpKit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class MpAccessTokenSevice {
	private final static String tencent_mp_access_token = "tencent_mp_access_token";
	private final static String accesstoken_url = "https://api.weixin.qq.com/cgi-bin/token";;
	
	@Autowired
	private RedisService redisService;
	
	/**
	 * 公众号和小程序均可以使用AppID和AppSecret调用本接口来获取access_token
	 * @param appid
	 * @param secret
	 * @return
	 * @throws DevMException
	 */
	public String getAccessToken(String appid, String secret)  throws DevMException{
		String access_token = null;
		if (redisService.hasKey(tencent_mp_access_token)) {
			access_token = redisService.get(tencent_mp_access_token).toString();
			log.info("从redis中获取access_token --> " + access_token);
		} else {
			Map<String, String> params = new HashMap<String, String>();
			// 获取token执行体
			params.put("grant_type", "client_credential");
			params.put("appid", appid);
			params.put("secret", secret);
			String jstoken = HttpKit.get(accesstoken_url, params);
			JSONObject json = JSONObject.parseObject(jstoken);
			if (json.getIntValue("errcode") == 0) {
				access_token = json.getString("access_token"); // 获取到token并赋值保存
				if(access_token==null) {
					throw new DevMException("access_token获取失败");
				}
				int expires_in = json.getIntValue("expires_in");// 单位(秒)
				redisService.set(tencent_mp_access_token, access_token, expires_in);
				log.info("调用接口获取access_token并存入到redis中 --> " + access_token);
			} else {
				throw new DevMException(json.getString("errmsg"));
			}
		}
		return access_token;
	}
}
